<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\FutureService;
use app\common\library\UploadService;
use app\common\library\Sms;
use app\common\model\ArchiveCollect;
use app\common\model\FutureTrade;
use fast\Random;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{

    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'changeemail', 'changemobile', 'third', 'forget_pwd'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $user = \app\common\model\User::where('id', $this->auth->id)->field('id, username,nickname,mobile,email,avatar,balance,income')->find();
        $this->success('', $user);
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error('Invalid parameters');
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('Logged in successful', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        if (!$username || !$password) {
            $this->error('Invalid parameters');
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error('Email is incorrect');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('Mobile is incorrect');
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('Sign up successful', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('Logout successful');
    }

    /**
     * 修改会员信息
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->request('nickname');
        $user->nickname = $nickname;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     */
    public function reset_pwd()
    {
        $new_password = $this->request->request("new_password");
        $old_password = $this->request->request("old_password");
        if (!$new_password || !$old_password) {
            $this->error('Invalid parameters');
        }
        if (!Validate::regex($new_password, ".{6,16}")) {
            $this->error('password length 6-12');
        }
        if (!Validate::regex($new_password, ".{6,16}")) {
            $this->error('password length 6-12');
        }
        $password = Auth::instance()->getEncryptPassword($old_password, $this->auth->salt);
        if ($password != $this->auth->password) {
            $this->error('old password error');
        }
        $ret = $this->auth->changepwd($new_password, '', true);
        if ($ret) {
            $this->success('Reset password successful');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 找回密码
     */
    public function forget_pwd()
    {
        try {
            $username = $this->request->request("username");
            $email = $this->request->request("email");
            $new_password = $this->request->request("new_password");

            $validate = new Validate([
                'username' => 'require',
                'email' => 'require|email',
                'new_password' => 'require|min:6|max:12'
            ], [
                'username.require' => 'Username not null',
                'email.require' => 'email not null',
                'email.email' => 'email not null',
                'new_password.require' => 'new_password not null',
                'new_password.min' => 'password length 6-12',
                'new_password.max' => 'password length 6-12'
            ]);
            if (!$validate->check($this->request->request())) {
                exception($validate->getError());
            }

            $user = \app\common\model\User::where(['username' => $username, 'email' => $email])->find();
            if (empty($user)) {
                exception('Not find username and email');
            }

            //模拟一次登录
            $this->auth->direct($user->id);
            $ret = $this->auth->changepwd($new_password, '', true);
            if (!$ret) {
                exception('Fail');
            } else {
                $this->success('Forget password success');
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

    }

    /**
     * 更新头像
     */
    public function avatar(Request $request)
    {
        try {
            $avatar = $request->param('avatar');

            if (empty($avatar)) {
                exception('avatar not null');
            }
            $tmpFilePath = UploadService::uploadBase64Image($avatar);

            if (false === $tmpFilePath) {
                exception('Avatar upload fail');
            }

            $result = \app\common\model\User::where('id', $this->auth->id)->update(['avatar' => $tmpFilePath]);
            if (empty($result))
            {
                exception('Update fail');
            }

            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 排行榜
     */
    public function top()
    {
        try {
           $list = \app\common\model\User::where('status', \app\common\model\User::USER_STATUS_NORMAL)
               ->field('id,nickname,avatar,income')
               ->order('income', 'desc')
               ->limit(10)
               ->select();
            $this->success('', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 用户期货记录
     * @param Request $request
     */
    public function future(Request $request)
    {
        $status = $request->request('status');
        try {
            $list = \app\common\model\FutureTrade::alias('ft')
                ->join('fa_future f', 'ft.future_id = f.id')
                ->where(['ft.status' => $status, 'ft.user_id' => $this->auth->id])
                ->field('ft.id,ft.status,f.symbol,f.code,f.name,ft.type,ft.buy_price,ft.num,ft.fee,ft.security_deposit,ft.total_overnight_fee,ft.total_income,ft.created_at')
                ->order('ft.created_at', 'desc')
                ->paginate();
            if(count($list) > 0){
                //拼接期货代码 查询期货实时价格
                $symbols = [];
                foreach ($list as $r){
                    $symbols[] = $r->symbol;
                }
                $response = FutureService::getInstance()->getComrms(implode(',', $symbols));
                foreach ($list as $r){
                    foreach ($response->Obj as $key => $item) {
                        if ($item->S == $r->code) {
                            $r->data("now_price", $item->P);
                            $r->data("income", ($item->P * 10 * $r->num) - ($r->buy_price * 10 * $r->num));
                        }
                    }
                }
            }
            $this->success('', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 平仓结算
     * @param Request $request
     * @throws \Exception
     */
    public function future_liquidation(Request $request)
    {
        $future_trade_id = $request->request('tuture_trade_id');
        try {

            $future_trade = FutureTrade::where(['id' => $future_trade_id, 'user_id' => $this->auth->id, 'status' => FutureTrade::IS_NOT_LIQUIDATION])->find();
            if (empty($future_trade)) {
                exception('Not find');
            }
            $future = \app\common\model\Future::where('id', $future_trade->future_id)->find();
            $response = FutureService::getInstance()->getComrms($future->symbol);

            $income = ($response->Obj[0]->P * $future_trade->num) - ($future_trade->buy_price * $future_trade->num);
            $future_trade->status = FutureTrade::IS_LIQUIDATION;
            $future_trade->open_time = time();
            $future_trade->sell_price = $response->Obj[0]->P;
            $future_trade->total_income = $income;
            $future_trade->save();

            //更新用户账户余额
            \app\common\model\User::changeBalance($this->auth->id, $income + $future_trade->security_deposit);
            //更新用户收益
            \app\common\model\User::changeIncome($this->auth->id, $income);

            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }


    /**
     * 用户收藏列表
     */
    public function collect_list(Request $request)
    {
        try {
            $list = Db::table('fa_archive_collect')->alias('c')
                ->join('fa_cms_archives a', 'c.aid = a.id')
                ->join('fa_cms_addonnews n', 'a.id = n.id')
                ->where(['c.user_id' => $this->auth->id])
                ->field('a.id,a.title,a.description,a.image,a.createtime,a.publishtime,n.source')
                ->order('c.created_at desc')
                ->paginate()
                ->toArray();
            if (!empty($list)) {
                foreach ($list['data'] as $key => $item) {
                    if (strpos($item['image'], '://')) {
                        $list['data'][$key]['image'] = $item['image'];
                    } else {
                        $list['data'][$key]['image'] = 'http://licai.ttzq520.cn' . $item['image'];
                    }
                }
            }
            $this->success('', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

}
